<template>
	<!-- 商品列表 -->
	<view>
		<view class="goods-list">
			<view v-for="(goods, i) in goodsList" :key="i" @click="gotoDetail(goods.goods_id)">
				<my-goods :goods="goods"></my-goods>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 请求参数对象
				queryObj: {
					// 查询关键词
					query: '',
					// 商品分类Id
					cid: '',
					// 页码值
					pagenum: 1,
					// 每页显示多少条数据
					pagesize: 10
				},

				goodsList: [],
				total: 0,
				isLoding: false,


			};
		},

		onLoad(options) {
			// console.log(options);
			// 将页面参数转存到 this.queryObj 对象中
			this.queryObj.query = options.query || ''
			this.queryObj.cid = options.cid || ''

			this.getGoodsList()
		},
		methods: {
			async getGoodsList(cb) {
				this.isLoding = true
				const {
					data: res
				} = await uni.$http.get('/api/public/v1/goods/search', this.queryObj)
				this.isLoding = false

				// 接收 cb 回调函数并按需进行调用：
				// 只要数据请求完毕，就立即按需调用 cb 回调函数
				cb && cb()

				if (res.meta.status !== 200) return uni.$showMsg()
				this.goodsList = [...this.goodsList, ...res.message.goods]
				this.total = res.message.total
			},

			gotoDetail(goodsId) {
				uni.navigateTo({
					url: '/subpkg/goods_detail/goods_detail?goods_id=' + goodsId
				})
			},

		},
		// 下拉刷新
		onPullDownRefresh() {
			// 重置数据
			this.queryObj.pagenum = 1
			this.total = 0
			this.isLoding = false
			this.goodsList = []

			// 重新发起请求
			this.getGoodsList(() => uni.stopPullDownRefresh())
		},

		onReachBottom() {
			if (this.queryObj.pagenum * this.queryObj.pagesize >= this.total)
				return uni.$showMsg('数据加载完毕！')

			// 判断是否正在请求其它数据，如果是，则不发起额外的请求
			if (this.isLoding) return

			this.queryObj.pagenum++
			this.getGoodsList()
		},

	}
</script>

<style lang="scss">

</style>
